/**
 * Copyright (C), 2017-2018, XXX有限公司
 * FileName: UnitPanel2
 * Author:   zengjian
 * Date:     2018/8/14 11:01
 * Description: 单元测试生成面板
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package fun.codedesign.yinxue.code.ui;

import fun.codedesign.yinxue.code.php2java.model.PhpProject;
import fun.codedesign.yinxue.code.php2java.service.Php2JavaService;
import fun.codedesign.yinxue.config.UserConfig;
import fun.codedesign.yinxue.util.LogUtil;
import fun.codedesign.yinxue.util.batch.BatchFileUtil;
import fun.codedesign.yinxue.util.batch.filter.PhpFilter;
import org.yinxue.swing.core.domain.FileObject;
import org.yinxue.swing.core.panel.YxUnitPanel;
import org.yinxue.swing.core.util.SwingUtils;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import static javax.swing.WindowConstants.HIDE_ON_CLOSE;

/**
 * 〈单元测试生成面板〉<br>
 * 〈一句话描述〉
 *
 * @author zengjian
 * @create 2018/8/14 11:01
 */
public class PhpPanel2 extends YxUnitPanel {

    PhpProject phpProject = new PhpProject();

    public PhpPanel2() {
        super();
    }

    @Override
    public void position() {
        // 重写部分组件字段
        super.position();
        String constructCode = "construct";
        String methodCode = "method";
        String controllerCode = "controller";
        String serviceCode = "service";
        String helperCode = "helper";
        String modelCode = "model";

        jLabel_unit.setText("php代码示例");
        jComboBox_unitType.removeAllItems();
        jComboBox_unitType.addItem(constructCode);
        jComboBox_unitType.addItem(methodCode);
        jComboBox_unitType.addItem(controllerCode);
        jComboBox_unitType.addItem(serviceCode);
        jComboBox_unitType.addItem(helperCode);
        jComboBox_unitType.addItem(modelCode);

        jComboBox_unitType.addItemListener(e -> {
            String selectItem = (String) e.getItem();
            if (constructCode.equals(selectItem)) {
                topInput.setText(Php2JavaService.phpExampleCodeConstruct());
            } else if (methodCode.equals(selectItem)) {
                topInput.setText(Php2JavaService.phpExampleCodeMethod());
            } else if (controllerCode.equals(selectItem)) {
                topInput.setText(Php2JavaService.phpExampleCodeController());
            } else if (serviceCode.equals(selectItem)) {
                topInput.setText(Php2JavaService.phpExampleCodeService());
            } else if (helperCode.equals(selectItem)) {
                topInput.setText(Php2JavaService.phpExampleCodeHelper());
            } else if (modelCode.equals(selectItem)) {
                topInput.setText(Php2JavaService.phpExampleCodeModel());
            }
        });
    }

    @Override
    public void action() {
        super.action();
        topInput.append(Php2JavaService.phpExampleCodeConstruct());
        rightInfo.append("我是php小助手，来试试我的[一键执行]吧！\n");
        jButton_generate.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (0 == jComboBox_operateType.getSelectedIndex()) {
                    try {
                        downOutput.setText(Php2JavaService.getContext(topInput.getText()).getText());
                    } catch (Exception e1) {
                        LogUtil.error(this, "生成失败", e1);
                        rightInfo.append(e1.getClass() + ":" + e1.getMessage());
                    }
                } else if (1 == jComboBox_operateType.getSelectedIndex()) {
                    openContext();
                    final String path = getAndSetInputPath();
                    threadPool().submitSingle(() -> {
                        long now = System.currentTimeMillis();
                        mailBox().sendMessage("批量读取java文件...");
                        Integer count = phpProject.generateJavaFile();
                        long now2 = System.currentTimeMillis();
                        long seconds = (now2 - now) / 1000;
                        mailBox().sendMessage("生成单元测试文件:" + count + "个，耗时:" + seconds +"秒");
                    });
                } else if (2 == jComboBox_operateType.getSelectedIndex()) {
                    threadPool().submitSingle(() -> {
                        mailBox().sendMessage("回滚开始...");
                        int count = BatchFileUtil.rollBack("E:\\log\\list.txt");
                        mailBox().sendMessage("回滚结束:" + count + "个文件已回滚!\n");
                    });
                } else {

                }
            }
        });

        jCheckBox_isPojo.addItemListener(e -> {
            if (e.getStateChange() == ItemEvent.SELECTED) {
//                    Context.config().setPojo(true);
            } else if (e.getStateChange() == ItemEvent.DESELECTED) {
//                    Context.config().setPojo(false);
            } else {
                throw new RuntimeException("你到了不可到达的区域，很神奇！");
            }
        });

        jButton_open.addActionListener(e -> threadPool().submitSingle(() -> {
            openContext();
        }));


        jComboBox_operateType.addItemListener(e -> {
            int chooseIndex = jComboBox_operateType.getSelectedIndex();
            // 先复位，避免勾选
            jCheckBox_isPojo.setSelected(false);
            if (chooseIndex == 0) {
                jCheckBox_isPojo.setVisible(true);
            } else if (chooseIndex == 1 || chooseIndex == 2) {
                jCheckBox_isPojo.setVisible(false); // 修改为隐藏
            } else {
                // Dothing
            }
            // 将设置的状态置为false，避免批量生成时取值错误
//                Context.config().setPojo(false);
        });

//        jButton_diy.addActionListener(new ActionListener() {
//            @Override
//            public void actionPerformed(ActionEvent e) {
//                SwingUtilities.invokeLater(new Runnable() {
//                    @Override
//                    public void run() {
//                        ConfigFrame.singleton.setVisible(true);
//                        ConfigFrame.singleton.setSpecClassDesc(Context.config().getSpecClassDesc());
//                    }
//                });
//            }
//        });

    }

    void openContext(){
        long time = System.currentTimeMillis();
        mailBox().sendMessage("容器开启...");
        BatchFileUtil.batchReadFileByThread(phpProject.path, new PhpFilter(), path -> {
            phpProject.addPhpFile(new FileObject(path.getName(), path));
            return null;
        });
        mailBox().sendMessage("容器开启完成，耗时:" + (System.currentTimeMillis() - time) + "ms");
        mailBox().sendMessage("容器包含类解析实例：" + phpProject.fileSize() + "个\n");
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
//                SwingUtils.initDefaultUI();
            JFrame jFrame = SwingUtils.ofJFrameWithMenuBar("yinxue-php", 1280, 760, new PhpPanel2());
            jFrame.setIconImage(new ImageIcon("icon/app_icon.png").getImage());
            jFrame.setVisible(true);
        });
    }

    public static void run() {
        SwingUtilities.invokeLater(() -> {
//                SwingUtils.initDefaultUI();
            JFrame jFrame = SwingUtils.ofJFrameWithMenuBar("yinxue-php", 800, 600, new PhpPanel2());
            jFrame.setIconImage(new ImageIcon("icon/app_icon.png").getImage());
            jFrame.setDefaultCloseOperation(HIDE_ON_CLOSE);
            jFrame.setVisible(true);
        });
    }


}